package listen

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gookit/event"
	"github.com/thinkeridea/go-extend/exunicode/exutf8"
	"github.com/vueadmin/app/admin/model"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/conv"
	"go.uber.org/zap"
	"strings"
	"unicode/utf8"
)

// 监听异常事件
func ExceptionLogEventListen(e event.Event) error {
	var data model.AdminLog
	handle := e.Data()["handle"].(*gin.Context)

	var content map[string]interface{}
	handle.ShouldBind(&content)

	for key, val := range content {
		if utf8.RuneCountInString(conv.String(val)) > 200 {
			content[key] = exutf8.RuneSubString(conv.String(val), 0, 200)
		}
	}

	str, _ := json.Marshal(content)

	data.ApplicationName = strings.Split(strings.TrimLeft(handle.Request.RequestURI, "/"), "/")[0]
	data.Username = "admin"
	data.Ip = utils.GetClientIP(handle)
	data.Url = "http://" + handle.Request.Host + handle.Request.RequestURI
	data.Useragent = handle.Request.UserAgent()
	data.Type = 3
	data.CreateTime = conv.NowUnix()
	data.Content = string(str)
	data.Errmsg = conv.String(e.Data()["errMsg"])

	if err := global.DB.Create(&data).Error; err != nil {
		global.LOG.Error(err.Error())
	}

	global.LOG.Error("[Recovery from panic]",
		zap.Any("error", e.Data()["errMsg"]),
		zap.String("request", handle.Request.Method),
		zap.String("request", handle.Request.RequestURI),
	)

	return nil
}
